package distMoney;

import java.util.ArrayList;
import java.util.Arrays;

public class Solution {
    public int distMoney(int money, int children) {

        int avrage = money/children;
        int restMoney =  money%children;
        int []arr = new int[children];
        if(avrage==0){
            return -1;
        }
        if(avrage>=8&& restMoney>0){
            return children-1;
        }

        if(avrage==8&&restMoney==0){
            return children;
        }

        for (int i = 0; i < children; i++) {
            arr[i]=avrage;
        }



        int p1 = 0;
        int p2 = 1;
        while(p1<arr.length&&p2<arr.length){
            int need = 8 - arr[p1];
            int tmp = Math.min(need,arr[p2]-1);
            arr[p1]+= tmp;
            arr[p2]-= tmp;
            if(arr[p1]==8){
                p1++;
                p2++;
            }
            if(arr[p2]==1){
                p2++;
            }
        }
        while(restMoney>0){
            int need= 8 - arr[p1]; // 1
            int tmp = Math.min(restMoney,need); // 1
            arr[p1]+=tmp; // 8
            restMoney-=tmp; //
            p1++;
        }
        for (int i = 0; i < children; i++) {
            if(arr[i]==4){
                if(i+1<children){
                    arr[i+1]++;
                    arr[i]--;
                }else if(i-1>=0){
                    arr[i-1]++;
                    arr[i]--;
                }
            }
        }
        int count=0;
        for (int i = 0; i < children; i++) {
            if(arr[i]==8){
                count++;
            }else if(arr[i]==4){
                count=-1;
            }
        }
        System.out.println(Arrays.toString(arr));
        return count;
    }
    // 20 3 2
    // 6 6 6
    // 8 4 6
    // 8
}